package com.hdaccp.xingmu.controller;

import com.hdaccp.xingmu.dao.JiaofeidanDao;
import com.hdaccp.xingmu.entity.House;
import com.hdaccp.xingmu.entity.Jiaofei;
import com.hdaccp.xingmu.entity.Jiaofeidan;
import com.hdaccp.xingmu.noentity.random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.criteria.Predicate;

@Controller
@RequestMapping("/jiaofeidan")
public class JiaofeidanCon {
    @Autowired
    private JiaofeidanDao jiaofeidanDao;

    @RequestMapping("/tiao")
    public String tiao(){
        return "WEB-INF/jsp/grfx";
    }


    @RequestMapping("/add")
    @ResponseBody
    public Jiaofeidan add(Jiaofeidan jiaofeidan){

        random ran = new random();
        String dd = ran.r();
        jiaofeidan.setOrderid(dd);


        return jiaofeidanDao.save(jiaofeidan);
    }

    @RequestMapping("/aa")
    @ResponseBody
    public List<Jiaofeidan> aaa(){

       return jiaofeidanDao.findAll();
    }

    @RequestMapping("/list")
    @ResponseBody
    public Map<String,Object> list(int name ,int pageNumber,int pageSize){


        Pageable pageable = new PageRequest((pageNumber-1),pageSize);
        Specification specification = new Specification<House>(){
            @Override
            public Predicate toPredicate(Root<House> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<Predicate>();

                if(name!=-1){
                    predicates.add(criteriaBuilder.equal(root.get("house").get("id"),name));
                }


                Predicate[] p = new Predicate[predicates.size()];
                return criteriaBuilder.and(predicates.toArray(p));
            }
        };

        List<Jiaofeidan> all2 = jiaofeidanDao.findAll(specification);
        Page<Jiaofeidan> all = jiaofeidanDao.findAll(specification,pageable);
        int zhong = all2.size();
        System.out.println(all2.size());
        List<Jiaofeidan> list = all.getContent();


        Map<String,Object> map=new HashMap<String,Object>();
        map.put("total",zhong);
        map.put("rows",list);

        return map;
    }



}
